package com.ly.lypopupwindowdemo.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ListPopupWindow;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.ly.lypopupwindowdemo.R;

public class AutoLocatedActivity extends AppCompatActivity {

    private ListPopupWindow listPopupWindow;
    private String[] datas;
    private ArrayAdapter<String> myAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto_located);

        datas = new String[]{"周杰伦","张艺兴","sheldon","Penny","HarryPotter","golss","金龙国"};
        myAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,datas);
    }

    public void showListPop(View view){

        if (listPopupWindow==null){
            listPopupWindow=new ListPopupWindow(this);
        }
        listPopupWindow.setAdapter(myAdapter);
        listPopupWindow.setWidth(300);//设置下拉窗口的宽度
        listPopupWindow.setHeight(500);//设置下拉窗口的高度
        //设置pop显示在哪个控件下面  （anchor 靠山）
        listPopupWindow.setAnchorView(view);//设置下拉窗口的参照控件，如果不设置窗口不知道显示在哪里就会异常堆出

        /**
         * setDropDownGravity : 设置下拉列表的对齐方式。
         * Gravity.START表示与参照控件左侧对齐，Gravity.END表示与参照控件右侧对齐。
         * 注意：该函数只在4.4.2及以上版本中使用。
         */

        listPopupWindow.setDropDownGravity(Gravity.START);
        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(AutoLocatedActivity.this, "选择了"+datas[position], Toast.LENGTH_SHORT).show();
                listPopupWindow.dismiss();

            }
        });

        listPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //下拉列表关闭监听器
                Toast.makeText(AutoLocatedActivity.this, "触发下拉列表关闭监听器", Toast.LENGTH_SHORT).show();
            }
        });
        listPopupWindow.show();
    }
}
